//
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

export interface IUser extends mongoose.Document {
  username: string;
  email: string;
  password: string;
  role: 'user' | 'admin';
  avatar?: string;
  comparePassword(candidatePassword: string): Promise<boolean>;
}

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, '用户名不能为空'],
    unique: true,
    trim: true,
    minlength: [3, '用户名至少需要3个字符']
  },
  email: {
    type: String,
    required: [true, '邮箱不能为空'],
    unique: true,
    trim: true,
    lowercase: true,
    match: [/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/, '请输入有效的邮箱地址']
  },
  password: {
    type: String,
    required: [true, '密码不能为空'],
    minlength: [6, '密码至少需要6个字符']
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  avatar: {
    type: String,
    default: function(this: any) {
      return `https://api.dicebear.com/7.x/avataaars/svg?seed=${this.username}`;
    }
  }
}, {
  timestamps: true
});

// 保存前加密密码
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) {
    return next();
  }
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error: any) {
    next(error);
  }
});

// 比较密码
userSchema.methods.comparePassword = async function(candidatePassword: string) {
  try {
    console.log('比较密码:', {
      candidatePassword,
      hashedPassword: this.password
    });
    const isMatch = await bcrypt.compare(candidatePassword, this.password);
    console.log('密码比较结果:', isMatch);
    return isMatch;
  } catch (error) {
    console.error('密码比较错误:', error);
    throw error;
  }
};

const User = mongoose.model<IUser>('User', userSchema);

export default User; 